<template>
  <div class="addContainer">
    <div style="
        height: 100%;
        padding-left: 150px;
        padding-right: 150px;
        overflow-y: auto;
        padding-bottom: 70px;
      ">
      <div style="padding: 20px">
        <el-card>
          <template #header>
            <span style="font-weight: bold; font-size: 16px">新增采购入库</span>
          </template>
          <div class="addBody">
            <el-form ref="formRef" :model="formData" :rules="formRules" label-width="120" style="margin-top: 20px">
              <div class="basicInfoContainer">
                <div class="milestone">
                  <div class="milestone-content">基础信息</div>
                </div>
                <div style="margin-top: 40px">
                  <el-row>
                    <el-col :span="12">
                      <el-form-item label="入库单编号" prop="stockInNo">
                        <el-input v-model="formData.stockInNo" placeholder="请输入" style="width: 300px">
                        </el-input>
                      </el-form-item>
                    </el-col>
                    <el-col :span="12">
                      <el-form-item label="入库单名称" prop="name">
                        <el-input v-model="formData.name" placeholder="请输入" style="width: 300px"></el-input>
                      </el-form-item>
                    </el-col>
                  </el-row>
                  <el-row>
                    <el-col :span="12">
                      <el-form-item label="入库日期" prop="stockInDate">
                        <el-date-picker v-model="formData.stockInDate" style="width: 300px" type="date"
                          placeholder="请选择日期" value-format="YYYY-MM-DD"></el-date-picker>
                      </el-form-item>
                    </el-col>
                    <el-col :span="12">
                      <el-form-item label="采购单名称" prop="purchaseOrderName">
                        <el-input v-model="formData.purchaseOrderName" placeholder="请输入"
                          style="width: 300px"></el-input>
                      </el-form-item>
                    </el-col>
                  </el-row>
                  <el-row>
                    <el-col :span="12">
                      <el-form-item label="采购单号" prop="purchaseOrderNo">
                        <el-input v-model="formData.purchaseOrderNo" placeholder="请选择成品"
                          style="width: 300px"></el-input>
                      </el-form-item>
                    </el-col>
                    <el-col :span="12">
                      <el-form-item label="供应商" prop="supplierName">
                        <el-select v-model="formData.supplierName" placeholder="请选择供应商" style="width: 300px">
                          <el-option v-for="item in supplierOptions" :key="item.name" :label="item.name"
                            :value="item.name"></el-option>
                        </el-select>
                      </el-form-item>
                    </el-col>
                  </el-row>
                  <el-row>
                    <el-col :span="12">
                      <el-form-item label="来料检验名称" prop="inspectionName">
                        <el-input v-model="formData.inspectionName" placeholder="请选择来料检验单"
                          style="width: 300px"></el-input>
                      </el-form-item>
                    </el-col>
                    <el-col :span="12">
                      <el-form-item label="来料检验单号" prop="inspectionNo">
                        <el-input v-model="formData.inspectionNo" placeholder="请输入" style="width: 300px"></el-input>
                      </el-form-item>
                    </el-col>
                  </el-row>
                  <el-form-item label="备注" prop="remark">
                    <el-input v-model="formData.remark" type="textarea" style="width: 795px" :rows="3"></el-input>
                  </el-form-item>
                </div>
              </div>
              <div class="bomContainer">
                <div class="bomInfoContainer">
                  <div class="milestone">
                    <div class="milestone-content">入库明细</div>
                  </div>
                  <div style="margin-top: 40px">
                    <el-row>
                      <el-col :span="12">
                        <el-form-item label="物料名称" prop="materialName">
                          <el-select v-model="formData.materialName" placeholder="请输入" style="width: 300px">
                            <el-option v-for="item in materialOptions" :key="item.name" :label="item.name"
                              :value="item.name"></el-option>
                          </el-select>
                        </el-form-item>
                      </el-col>
                      <el-col :span="12">
                        <el-form-item label="物料编号" prop="materialNo">
                          <el-input v-model="formData.materialNo" placeholder="请输入" style="width: 300px"></el-input>
                        </el-form-item>
                      </el-col>
                    </el-row>
                    <el-row>
                      <el-col :span="12">
                        <el-form-item label="规格型号" prop="specification">
                          <el-input v-model="formData.specification" placeholder="请输入" style="width: 300px"></el-input>
                        </el-form-item>
                      </el-col>
                      <el-col :span="12">
                        <el-form-item label="单位" prop="unit">
                          <el-input v-model="formData.unit" placeholder="请输入" style="width: 300px"></el-input>
                        </el-form-item>
                      </el-col>
                    </el-row>
                    <el-row>
                      <el-col :span="12">
                        <el-form-item label="生产日期" prop="productionDate">
                          <el-date-picker v-model="formData.productionDate" style="width: 300px" type="date"
                            placeholder="请选择日期" value-format="YYYY-MM-DD"></el-date-picker>
                        </el-form-item>
                      </el-col>
                      <el-col :span="12">
                        <el-form-item label="到期日期" prop="expiryDate">
                          <el-date-picker v-model="formData.expiryDate" style="width: 300px" type="date"
                            placeholder="请选择日期" value-format="YYYY-MM-DD"></el-date-picker>
                        </el-form-item>
                      </el-col>
                    </el-row>
                    <el-row>
                      <el-col :span="12">
                        <el-form-item label="批次号" prop="batchNo">
                          <el-input v-model="formData.batchNo" placeholder="请输入" style="width: 300px"></el-input>
                        </el-form-item>
                      </el-col>
                      <el-col :span="12">
                        <el-form-item label="入库数量" prop="stockInQuantity">
                          <el-input-number v-model="formData.stockInQuantity" placeholder="请输入" style="width: 300px"
                            :min="1" :precision="0"></el-input-number>
                        </el-form-item>
                      </el-col>
                    </el-row>
                    <el-row>
                      <el-col :span="12">
                        <el-form-item label="仓库名称" prop="warehouseName">
                          <el-select v-model="formData.warehouseName" placeholder="请选择仓库名称" style="width: 300px"
                            @change="handleWarehouseChange">
                            <el-option v-for="item in warehouseOptions" :key="item.value" :label="item.label"
                              :value="item.value"></el-option>
                          </el-select>
                        </el-form-item>
                      </el-col>
                      <el-col :span="12">
                        <el-form-item label="仓库负责人" prop="warehouseManager">
                          <el-input v-model="formData.warehouseManager" placeholder="请输入"
                            style="width: 300px"></el-input>
                        </el-form-item>
                      </el-col>
                    </el-row>
                    <el-row>
                      <el-col :span="12">
                        <el-form-item label="库区名称" prop="zoneName">
                          <el-select v-model="formData.zoneName" placeholder="请选择库区" style="width: 300px"
                            @change="handleZoneChange">
                            <el-option v-for="item in zoneOptions" :key="item.value" :label="item.label"
                              :value="item.value"></el-option>
                          </el-select>
                        </el-form-item>
                      </el-col>
                      <el-col :span="12">
                        <el-form-item label="库位名称" prop="locationName">
                          <el-select v-model="formData.locationName" placeholder="请选择库位" style="width: 300px">
                            <el-option v-for="item in locationOptions" :key="item.value" :label="item.label"
                              :value="item.value"></el-option>
                          </el-select>
                        </el-form-item>
                      </el-col>
                    </el-row>
                  </div>
                </div>
              </div>
            </el-form>
          </div>
        </el-card>
      </div>
    </div>
    <div class="footer" :class="{ 'footer-visible': isFooterVisible }">
      <div class="footerButton">
        <el-button type="primary" plain style="width: 80px" @click="close">关闭</el-button>
        <el-button type="primary" style="width: 80px" @click="submitForm" :loading="submitting">确定</el-button>
      </div>
    </div>

    <!-- 选择物料对话框 -->
    <MaterialDialog v-model="materialDialogVisible" @select="handleMaterialSelect" />

    <!-- 选择供应商对话框 -->
    <SupplierDialog v-model="supplierDialogVisible" @select="handleSupplierSelect" />
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from "vue";
import { useRouter } from "vue-router";
import { ElMessage, type FormInstance, type FormRules } from "element-plus";
import { postStockInAddApi } from "@/api/Buy";

const $router = useRouter();
const formRef = ref<FormInstance>();
const submitting = ref(false);
const materialDialogVisible = ref(false);
const supplierDialogVisible = ref(false);

// 物料选择对话框
const materialOptions = ref([
  { no: "MAT001", name: "铝合金板", spec: "AL-6061 10mm", unit: "张" },
  { no: "MAT002", name: "不锈钢螺丝", spec: "M6×20", unit: "个" },
  { no: "MAT003", name: "PVC管", spec: "Φ50×3m", unit: "根" },
]);

// 供应商选择对话框
const supplierOptions = ref([
  { no: "SUP001", name: "华东材料有限公司" },
  { no: "SUP002", name: "北方工业集团" },
  { no: "SUP003", name: "南方五金供应商" },
]);

// 选择物料
const selectMaterial = (material: any) => {
  formData.materialName = material.name;
  formData.materialNo = material.no;
  formData.specification = material.spec;
  formData.unit = material.unit;
  materialDialogVisible.value = false;
};

// 选择供应商
const selectSupplier = (supplier: any) => {
  formData.supplierName = supplier.name;
  formData.supplierNo = supplier.no;
  supplierDialogVisible.value = false;
};
// 仓库相关选项
const warehouseOptions = ref([
  { value: "成品仓", label: "成品仓" },
  { value: "原材料仓", label: "原材料仓" },
  { value: "半成品仓", label: "半成品仓" },
]);

const zoneOptions = ref<Array<{ value: string; label: string }>>([]);
const locationOptions = ref<Array<{ value: string; label: string }>>([]);

// 表单数据
const formData = reactive({
  name: "",
  stockInNo: "",
  stockInDate: "",
  purchaseOrderName: "",
  purchaseOrderNo: "",
  supplierName: "",
  supplierNo: "",
  inspectionName: "",
  inspectionNo: "",
  remark: "",

  materialName: "",
  materialNo: "",
  specification: "",
  unit: "",
  productionDate: "",
  expiryDate: "",
  batchNo: "",
  stockInQuantity: 1,
  warehouseName: "",
  zoneName: "",
  locationName: "",
  warehouseManager: "张管理员",
});

// 表单验证规则
const formRules: FormRules = {
  name: [{ required: true, message: "请输入入库单名称", trigger: "blur" }],
  stockInNo: [{ required: true, message: "请输入入库单编号", trigger: "blur" }],
  stockInDate: [
    { required: true, message: "请选择入库日期", trigger: "change" },
  ],
  materialName: [{ required: true, message: "请选择物料", trigger: "blur" }],
  materialNo: [
    { required: true, message: "物料编号不能为空", trigger: "blur" },
  ],
  stockInQuantity: [
    { required: true, message: "请输入入库数量", trigger: "blur" },
  ],
  warehouseName: [{ required: true, message: "请选择仓库", trigger: "change" }],
  zoneName: [{ required: true, message: "请选择库区", trigger: "change" }],
  locationName: [{ required: true, message: "请选择库位", trigger: "change" }],
};
const isFooterVisible = ref(false);

// 选择物料
const showMaterialDialog = () => {
  materialDialogVisible.value = true;
};

const handleMaterialSelect = (material: any) => {
  formData.materialName = material.name;
  formData.materialNo = material.no;
  formData.specification = material.spec;
  formData.unit = material.unit;
};

// 选择供应商
const showSupplierDialog = () => {
  supplierDialogVisible.value = true;
};

const handleSupplierSelect = (supplier: any) => {
  formData.supplierName = supplier.name;
  formData.supplierNo = supplier.no;
};

// 仓库选择变化
const handleWarehouseChange = (val: string) => {
  formData.zoneName = "";
  formData.locationName = "";

  // 模拟根据仓库获取库区
  if (val === "成品仓") {
    zoneOptions.value = [
      { value: "成品A区", label: "成品A区" },
      { value: "成品B区", label: "成品B区" },
    ];
  } else if (val === "原材料仓") {
    zoneOptions.value = [
      { value: "原料A区", label: "原料A区" },
      { value: "原料B区", label: "原料B区" },
    ];
  } else {
    zoneOptions.value = [];
  }
};

// 库区选择变化
const handleZoneChange = (val: string) => {
  formData.locationName = "";

  // 模拟根据库区获取库位
  if (val === "成品A区") {
    locationOptions.value = [
      { value: "A-01-01", label: "A-01-01" },
      { value: "A-01-02", label: "A-01-02" },
    ];
  } else if (val === "成品B区") {
    locationOptions.value = [
      { value: "B-01-01", label: "B-01-01" },
      { value: "B-01-02", label: "B-01-02" },
    ];
  } else {
    locationOptions.value = [];
  }
};

// 提交表单
const submitForm = async () => {
  try {
    await formRef.value?.validate();

    submitting.value = true;

    // 提交数据
    const response = await postStockInAddApi({
      ...formData,
      state:true,
      stockInQuantity: formData.stockInQuantity.toString(),
    });

    ElMessage.success("新增入库单成功");
    $router.replace("/storage/entrance/buy");
  } catch (error) {
    console.error("提交失败:", error);
    ElMessage.error("提交失败，请检查表单");
  } finally {
    submitting.value = false;
  }
};

// 关闭页面
const close = () => {
  $router.replace("/storage/entrance/buy");
};

onMounted(() => {
  setTimeout(() => {
    isFooterVisible.value = true;
  }, 100);
  // 设置默认日期为今天
  const today = new Date();
  formData.stockInDate = `${today.getFullYear()}-${String(
    today.getMonth() + 1
  ).padStart(2, "0")}-${String(today.getDate()).padStart(2, "0")}`;
});
</script>

<style scoped lang="scss">
/* 保持原有样式不变 */
.addContainer {
  width: 100%;
  position: relative;
  height: 100%;
  transform: translate(0);

  .addBody {
    width: 100%;

    .basicInfoContainer,
    .bomInfoContainer {
      padding: 20px;

      .milestone {
        width: 100%;
        display: flex;
        align-items: center;
        justify-content: center;
        height: 1.5px;
        background-color: #dfe2e7;

        .milestone-content {
          border: 1.5px solid #dfe2e7;
          padding: 10px;
          padding-left: 20px;
          padding-right: 20px;
          font-weight: bold;
          font-size: 15px;
          border-radius: 10px;
          z-index: 999;
          background-color: #fff;
          color: #1b9aee;
        }
      }
    }

    .bomInfoContainer {
      margin-top: 20px;
    }
  }

  .footer {
    z-index: 999;
    width: 100%;
    height: 70px;
    background-color: #fff;
    position: fixed;
    bottom: 0;
    left: 0;
    padding: 10px;
    display: flex;
    justify-content: center;
    box-shadow: 0 -8px 10px rgba(92, 92, 92, 0.1);
    transform: translateY(100%); // 初始状态在视口下方
    transition: transform 0.5s ease-out; // 添加过渡效果

    &.footer-visible {
      transform: translateY(0); // 显示时回到原位
    }
  }
}
</style>